<?php

namespace App\Http\Controllers;

use App\Models\Member;
use EasyWeChat\Foundation\Application;
use EasyWeChat\OpenPlatform\Guard;
use EasyWeChat\Message\Text;
use Illuminate\Http\Request;

class WechatController extends Controller
{
    //
    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve(Request $request)
    {

        $wechatConfig = config('wechat');
        $app = new Application($wechatConfig);
        $openPlatform = $app->open_platform;

        $authorizationInfo = \DB::table("open_platform")->where('app','wx2b4fa3fce5bef950')->first();
        $wechatApp = $openPlatform->createAuthorizerApplication($authorizationInfo->app_id , $authorizationInfo->refresh_token);

        $wechatApp->server->setMessageHandler(function($message) use ($wechatApp , $openPlatform) {
            $user_openid = $message->FromUserName;   //获取用户id
            \Log::debug(json_encode($message));
            if($message->MsgType == 'text'){
                if($message->Content == 'TESTCOMPONENT_MSG_TYPE_TEXT'){
                    return 'TESTCOMPONENT_MSG_TYPE_TEXT_callback';
                }
                if(strpos($message->Content , 'QUERY_AUTH_CODE')!== false){
                    $authCode = str_replace('QUERY_AUTH_CODE:' , '' , $message->Content);
                    $res = $openPlatform->getAuthorizationInfo($authCode);
                    $appid = $res->authorization_info['authorizer_appid'];
                    $refresh_token = $res->authorization_info['authorizer_refresh_token'];
                    $wechatApp = $openPlatform->createAuthorizerApplication($appid , $refresh_token);
                    $staff = $wechatApp->staff;
                    $staffMessage = new Text(['content' =>  $authCode.'_from_api']);
                    $staff->message($staffMessage)->to($user_openid)->send();
                }
                return '';
            }
            if ($message->MsgType == 'event') {
                if($user_openid == 'gh_3c884a361561'){
                    return $message->Event.'from_callback';
                }
                if ($message->Event == 'subscribe') {
                    //下面是你点击关注时，进行的操作
                    $user_info['openid'] = $user_openid;
                    $userService = $wechatApp->user;
                    $user = $userService->get($user_info['openid']);
                    $user_info['nickname'] = $user['nickname'];
                    //判断用户是否存在,存在的话就直接插入用户表
                    $mem_info = Member::where('openid',$user_openid)->first();
                    $res = false;
                    if(empty($mem_info)){
                        $res = Member::create($user_info);
                    }
//                    if ($res) {
////                        return '欢迎关注';
//                    } else {
////                        return '您的信息由于某种原因没有保存，请重新关注';
//                    }
                } else if ($message->Event == 'unsubscribe') {
                    //取消关注时执行的操作，（注意下面返回的信息用户不会收到，因为你已经取消关注，但别的操作还是会执行的<如：取消关注的时候，要把记录该用户从记录微信用户信息的表中删掉>）
                    \Log::debug('用户'.$user_openid.'取消关注');
                    $res = Member::where('openid',$user_openid)->delete();
                }
            }
        });

        return $wechatApp->server->serve();

    }


    public function openPlatform(){
        $wechatConfig = config('wechat');
        $app = new Application($wechatConfig);
        $openPlatform = $app->open_platform;

        $server = $openPlatform->server;
        $server->setMessageHandler(function($event) use ($openPlatform) {
            \Log::debug($event);
            // 事件类型常量定义在 \EasyWeChat\OpenPlatform\Guard 类里
            switch ($event->InfoType) {
                case Guard::EVENT_AUTHORIZED: // 授权成功
                    // 保存数据库操作等...
                    $authorizationInfo = $openPlatform->getAuthorizationInfo($event->AuthorizationCode);
                    $appid = $authorizationInfo->authorization_info['authorizer_appid'];
                    $refresh_token = $authorizationInfo->authorization_info['authorizer_refresh_token'];
                    \DB::table("open_platform")->where('app','wx2b4fa3fce5bef950')->where('app_id' , $appid)->update(['refresh_token' => $refresh_token]);
                    break;
                case Guard::EVENT_UPDATE_AUTHORIZED: // 更新授权
                    // 更新数据库操作等...
                    $authorizationInfo = $openPlatform->getAuthorizationInfo($event->AuthorizationCode);
                    $appid = $authorizationInfo->authorization_info['authorizer_appid'];
                    $refresh_token = $authorizationInfo->authorization_info['authorizer_refresh_token'];

                    \DB::table("open_platform")->where('app','wx2b4fa3fce5bef950')->where('app_id' , $appid)->update(['refresh_token' => $refresh_token]);
                    break;
                case Guard::EVENT_UNAUTHORIZED: // 授权取消
                    $authorizationInfo = $openPlatform->getAuthorizationInfo($event->AuthorizationCode);
                    $appid = $authorizationInfo->authorization_info['authorizer_appid'];
                    $refresh_token = $authorizationInfo->authorization_info['authorizer_refresh_token'];
                    \DB::table("open_platform")->where('app','wx2b4fa3fce5bef950')->where('app_id' , $appid)->update(['refresh_token' => $refresh_token]);
                    break;

            }
        });
        $response = $server->serve();

        return $response;
    }

    public function auth(){
        $options = config('wechat');
        $app = new Application($options);
        $openPlatform = $app->open_platform;
        $response = $openPlatform->pre_auth->redirect('http://open.guoxiaoge.cn/wxcallback');
        return view('auth' , ['url' => $response->getTargetUrl()]);
    }

    public function wxcallback(){
        $options = config('wechat');
        $app = new Application($options);
        $openPlatform = $app->open_platform;
        try{
            $res = $openPlatform->getAuthorizationInfo($authorizationCode = null);
            $appid = $res->authorization_info['authorizer_appid'];
            $refresh_token = $res->authorization_info['authorizer_refresh_token'];
            \DB::table("open_platform")->where('app','wx2b4fa3fce5bef950')->where('app_id' , $appid)->update(['refresh_token' => $refresh_token]);
            return 'Success';
        }catch (\Exception $ex){
            abort(404,$ex->getMessage());
        }
    }

}
